﻿using System.Diagnostics.CodeAnalysis;
using DimensionsHelper.Common.Contracts;

namespace DimensionsHelper.CommandLine;

public class ArgumentsReader
{
    private readonly Dictionary<string, string> _argMap;
    
    public ArgumentsReader(IList<string> args)
    {
        _argMap = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);

        foreach (string arg in args)
        {
            string[] argValues = arg.Split(Assignment, 2);
            string argV = argValues.Length > 1 ? argValues[1] : "";
            _argMap.TryAdd(argValues[0], argV);

            if (argValues[0] == JsonArgumentName)
            {
                JsonArgValue = argValues[1];
            }
            else if (argValues[0] == DetailReportLevelArgumentName)
            {
                ReportLevel = ReportLevel.Detail;
            }
        }

        OptionName = args.Count > 0 ? args[0] : string.Empty;
    }

    /// <summary>
    ///     获取或设置赋值操作符。
    /// </summary>
    public string Assignment { get; set; } = "=";

    /// <summary>
    ///     第一个参数的名字
    /// </summary>
    public string OptionName { get; }

    public static string JsonArgumentName { get; set; } = "-json";

    public static string DetailReportLevelArgumentName { get; set; } = "-detail";

    /// <summary>
    ///     参数列表中参数名是<see cref="JsonArgumentName" />的参数值。
    /// </summary>
    public string? JsonArgValue { get; private set; }

    /// <summary>
    ///     参数中配置的报告级别。
    /// </summary>
    public ReportLevel ReportLevel { get; set; } = ReportLevel.Brief;

    /// <summary>
    ///     获取指定参数名的参数值，可能是<see langword="null" />。
    /// </summary>
    /// <param name="argName">参数名，区分大小写</param>
    public string? GetArgValue(string argName)
    {
        return _argMap.GetValueOrDefault(argName);
    }


    /// <summary>
    ///     获取指定参数名的参数值
    /// </summary>
    public bool TryGetArgValue(string argName, [MaybeNullWhen(false)] out string argValue)
    {
        return _argMap.TryGetValue(argName, out argValue);
    }
}